#!/bin/bash
# Author: liuxu
# Date: 2025/8/4
# Description: 编译galaxy源码测试
# Usage method: export ./galaxy_build.sh

# 启用严格模式
set -euo pipefail

export SCRIPT_FULL_PATH=$(readlink -f "$0")
export SCRIPT_DIR=$(dirname ${SCRIPT_FULL_PATH})
export SCRIPT_NAME=$(basename ${SCRIPT_FULL_PATH})

# Check if the galaxy directory exists
if [ -d "galaxy" ]; then
    read -p "Detected existing 'galaxy' directory. Delete and re-clone? (y/N) " choice
    # Convert input to lowercase for easier judgment (supports Y/Yes etc.)
    choice=$(echo "$choice" | tr '[:upper:]' '[:lower:]')

    if [ "$choice" = "y" ] || [ "$choice" = "yes" ]; then
        rm -rf galaxy
        echo "Cleanup completed, preparing to clone repository..."
    else
        echo "User canceled deletion. Script terminated. Please handle the 'galaxy' directory manually and try again."
        exit 0  # Non-error exit, user-initiated cancellation
    fi
fi

# 拉取代码(北京gitlab：http://10.0.54.20/，乌镇gitlab：http://10.15.3.7/)
git clone --depth 1 --no-recurse-submodules  -b develop http://root:glpat-tWyMPqC9_3PVzz9kcoBB@10.15.3.7/dcutoolkit/driverruntime/galaxy.git

# 编译新的库文件
cd galaxy
rm -rf build
mkdir build && cd build
cmake -DADDRESS_SANITIZER=TRUE -DCMAKE_BUILD_TYPE=Debug -DROCM_PATH=${ROCM_PATH} -DLLVM_PATH=${ROCM_PATH}/llvm -DCMAKE_INSTALL_PREFIX="./dtk"  -DCMAKE_PREFIX_PATH=${ROCM_PATH} -DCMAKE_C_COMPILER=${ROCM_PATH}/llvm/bin/clang -DCMAKE_CXX_COMPILER=${ROCM_PATH}/llvm/bin/clang++ ..
make -j $(nproc)
make build_roofline # dtk-25.04.1工具链新增
make install

# 设置环境变量指向新库的路径
export LD_LIBRARY_PATH=$PWD/dtk/lib:$LD_LIBRARY_PATH
export PATH=$PWD/dtk/bin:$PATH

echo """Please execute the following commands:
export LD_LIBRARY_PATH=$PWD/dtk/lib:\$LD_LIBRARY_PATH
export PATH=$PWD/dtk/bin:\$PATH
ln -sf $ROCM_PATH/llvm/bin/dcc $PWD/dtk/hip/bin/hipcc
"""



# ASAN_OPTIONS=halt_on_error=0 LD_PRELOAD=$ROCM_PATH/llvm/lib/clang/15.0.0/lib/linux/libclang_rt.asan-x86_64.so hipprof --hip-trace --sqtt ./demo